package com.tonicgb.shared.Interceptor;

import com.tonicgb.shared.core.jwt.JWTToken;
import com.tonicgb.shared.common.enums.MessageCodeEnum;
import com.tonicgb.shared.common.enums.UserType;
import com.tonicgb.shared.exception.ApiException;
import com.tonicgb.shared.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author zhaiyujin
 * @date 2021-09-06 11:50:12
 * @说明 后端拦截控制
 */
public class AdminTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTToken JWTToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if(JWTToken.isPassToken((HandlerMethod)handler))
            return true;

        String token= JWTToken.getTokenFormRequest(request);
        if(token == null || token.isEmpty())
            throw new ApiException(MessageCodeEnum.UNAUTHORIZED);

        if( !JWTToken.check(token,UserType.ADMIN.getText()))
            throw new ApiException(MessageCodeEnum.UNAUTHORIZED);

        return  true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // ThreadLocal值清除，防止内存泄漏(ThreadLocal虽然可以自动回收这里我们手动清除)
        ThreadLocalUtil.remove();
    }



}
